<template>
	<view>
		<!-- 顶部占位栏（适配状态栏 + 导航栏） -->
			<view :style="{ height: statusBarHeight + 'px' }"></view>
	<view class="all">
		<!-- 帖子 -->
		<view>
			<view class="post">
				<view class="post-header">
					<img class="avatar" :src="'http://121.40.246.29/prod-api'+postList.communityUserNameDD.avatar" @click="toHomePage(postList.postUserId)"/>
					<view class="user-info">
						<span class="name">{{ postList.communityUserNameDD.userName }}</span>
						<span class="time">{{ postList.createTime }}</span>
					</view>
				</view>
				<view class="post-content">
					<view class="title">{{ postList.postTitle }}</view>
					<view class="details">{{ postList.postContent }}</view>
				</view>
				<view class="divider"></view>
			</view>
		</view>

		<!-- 评论 -->
		<view class="comment-section">
			<view v-for="(item, i) in commentList" :key="i" v-show="item.commentsParentsId === 0 && commentList!=null"
				class="comment-item">
				<view class="comment-header">
					<u-avatar class="avatar" :size="40" :src="'http://121.40.246.29/prod-api'+item.communityUserNameDD.avatar" @click="toHomePage(item.commentsUserId)"></u-avatar>
					<view class="user-info">
						<span class="author-name">{{ item.communityUserNameDD.userName }}</span>
						<span class="author-time">{{ item.commentsCreateTime }}</span>
					</view>
					<view class="action-buttons">
						<view class="action-btn" @click="showReplyInput(i, item.commentsId)">
							<u-icon name="chat" size="20" color="#d4a373"></u-icon>
							<text class="action-text">回复</text>
						</view>
						<view class="action-btn" @click="toAddUp(item.commentsId)">
							<u-icon name="thumb-up" size="20" color="#d4a373"></u-icon>
							<text class="action-text">{{ item.commentsUp }}</text>
						</view>
					</view>
				</view>
				<view class="comment-content">
					{{ item.commentsContent }}
				</view>
				
				<!-- 回复列表 -->
				<view class="reply-list" v-show="item.replyList">
					<view v-for="(reply,j) in item.replyList" :key="j" class="reply-item">
						<view class="reply-header">
							<u-avatar class="avatar" :size="36" :src="'http://121.40.246.29/prod-api'+reply.communityUserNameDD.avatar" @click="toHomePage(item.commentsUserId)"></u-avatar>
							<view class="user-info">
								<span class="author-name">{{reply.communityUserNameDD.userName}}</span>
								<span class="author-time">{{reply.commentsCreateTime}}</span>
							</view>
							<view class="action-buttons">
								<view class="action-btn" @click="() => showReplyInput(i, reply.commentsId)">
									<u-icon name="chat" size="18" color="#d4a373"></u-icon>
								</view>
								<view class="action-btn" @click="toAddUp(reply.commentsId)">
									<u-icon name="thumb-up" size="18" color="#d4a373"></u-icon>
									<text class="action-text">{{ reply.commentsUp }}</text>
								</view>
							</view>
						</view>
						<view class="reply-content">
							<text class="reply-to">回复 {{ item.communityUserNameDD.userName }}：</text>
							{{reply.commentsContent}}
						</view>
					</view>
				</view>
				
				<!-- 回复输入框 -->
				<view v-show="_inputShow(i)" class="reply-input-container">
					<input class="reply-input" placeholder="输入回复内容..." 
						@focus="showReplyBtn()" @input="onDivInput" />
					<button class="send-btn" @click="sendCommentReply()">发送</button>
				</view>
			</view>
		</view>
		
		<!-- 底部输入框 -->
		<view class="bottom-input-container">
			<input class="comment-input" placeholder="输入评论..." 
				@focus="showReplyBtn()" @input="onDivInput" />
			<button class="send-btn" @click="sendComment()">发送</button>
		</view>
		
		<!-- 加入按钮 -->
		<view class="join-btn" @click="toAdd()" v-show="this.change==1">
			<u-icon name="plus" size="24" color="#ffffff"></u-icon>
			<text>加入</text>
		</view>
	</view>
	</view>
</template>

<script>

	export default {
		
		data() {
			return {
				statusBarHeight: 0,
				 change: 0,
				//token用户信息
				userId: 0,
				userAVatar: null,
				postList: [],
				commentList: [],
				// avatar: null,
				beAddList:[],
				postId: 0,
				timeNow: null,
				btnId: '',
					// 新增：存储用户点赞状态的Map
							likedComments: new Map(), // 键为评论ID，值为是否点赞
				addForm: {
					commentsContent: "啦啦啦啦2",
					commentsUserId: 0,
					commentsPostId: 0,
					commentsUp: 0,
					commentsCreateTime: null,
					commentsParentsId: 0,
					commentsInputShow: 0
				},
				// 输入框
				btnShow: false,
				index: '0',
				replyComment: '',
				roles:''
			}
		},
		onLoad(option) {
			const systemInfo = uni.getSystemInfoSync();
					this.statusBarHeight = systemInfo.statusBarHeight || 0;
            console.log(option)
			this.postId = option.postId;
			this.getPost();
			this.tokenList = uni.getStorageSync("storage_data") || {};
			this.userId = this.tokenList.vuex_id
			this.userAVatar = this.tokenList.vuex_avatar
			this.addForm.commentsPostId = this.postId;
			this.addForm.commentsUserId = this.userId;
		},
		methods: {
			toHomePage(postUserId){
				uni.navigateTo({
					url: '/pages/mine/homePage/homePage?userId='+ postUserId
				})
			},
			nestComments(commentList) {
				const commentMap = {};
				const rootComments = [];

				commentList.forEach(comment => {
					comment.replyList = [];
					commentMap[comment.commentsId] = comment;
				});

				commentList.forEach(comment => {
					if (comment.commentsParentsId !== 0) {
						const parentComment = commentMap[comment.commentsParentsId];
						if (parentComment) {
							if (!parentComment.replyList) {
								parentComment.replyList = [];
							}
							parentComment.replyList.push(comment);
						}
					} else {
						rootComments.push(comment);
					}
				});

				return rootComments;
			},
			showReplyBtn() {
				this.btnShow = true
			},
			hideReplyBtn() {
				this.btnShow = false
			},
			showReplyInput(i, id) {
				this.index = i
				this.commentList[i].commentsInputShow = 1
				this.btnId = id
			},
			_inputShow(i) {
				return this.commentList[i].commentsInputShow
			},
			toAddUp(id) {
			  uni.request({
			    url: this.$BASE_URL.baseUrl + '/community/comments/' + id,
			    method: 'GET',
			    success: (res) => {
			      // 确认返回的是单个对象而非数组
			      if (Array.isArray(res.data.data)) {
			        this.beAddList = res.data.data[0]; // 取第一个元素（根据实际情况调整）
			      } else {
			        this.beAddList = res.data.data;
			      }
			      this.beAddList.commentsUp += 1;
			      // 立即发送更新请求
			      uni.request({
			        url: this.$BASE_URL.baseUrl + '/community/comments',
			        method: 'PUT',
			        header: { 'Content-Type': 'application/json' },
			        data: this.beAddList,
			        success: () => {
			          this.getPost(); // 刷新数据
			        }
			      });
			    }
			  });
			},
			  sendComment() {
			    if (!this.replyComment) {
			      uni.showToast({
			        title: '评论不能为空',
			        icon: 'none'
			      });
			      return;
			    }
			    
			    this.addForm.commentsContent = this.replyComment;
			    this.timeNow = new Date();
			    const formattedDate = 
			      `${this.timeNow.getFullYear()}-${this.padZero(this.timeNow.getMonth() + 1)}-${this.padZero(this.timeNow.getDate())} ${this.padZero(this.timeNow.getHours())}:${this.padZero(this.timeNow.getMinutes())}:${this.padZero(this.timeNow.getSeconds())}`;
			    
			    uni.request({
			      url: this.$BASE_URL.baseUrl + '/community/comments',
			      method: 'post',
			      header: {
			        'Content-Type': 'application/json'
			      },
			      data: {
			        commentsContent: this.addForm.commentsContent,
			        commentsCreateTime: formattedDate,
			        commentsUserId: this.addForm.commentsUserId,
			        commentsPostId: this.addForm.commentsPostId,
			        commentsUp: this.addForm.commentsUp,
			        commentsParentsId: 0,
			        commentsInputShow: 0,
			      },
			      success: () => {
			        uni.showToast({
			          title: '评论成功',
			          icon: 'success'
			        });
			        
			        this.btnId = '';
			        // 发送成功后刷新页面数据
			       
			        this.$nextTick(() => {
						this.replyComment = '';
			          this.getPost();
			        });
			      },
			      fail: () => {
			        uni.showToast({
			          title: '评论失败',
			          icon: 'error'
			        });
			      }
			    });
			  },
			  
			  sendCommentReply() {
			    if (!this.replyComment) {
			      uni.showToast({
			        title: '回复不能为空',
			        icon: 'none'
			      });
			      return;
			    }
			    
			    this.addForm.commentsContent = this.replyComment;
			    this.timeNow = new Date();
			    const formattedDate = 
			      `${this.timeNow.getFullYear()}-${this.padZero(this.timeNow.getMonth() + 1)}-${this.padZero(this.timeNow.getDate())} ${this.padZero(this.timeNow.getHours())}:${this.padZero(this.timeNow.getMinutes())}:${this.padZero(this.timeNow.getSeconds())}`;
			    
			    uni.request({
			      url: this.$BASE_URL.baseUrl + '/community/comments',
			      method: 'post',
			      header: {
			        'Content-Type': 'application/json'
			      },
			      data: {
			        commentsContent: this.addForm.commentsContent,
			        commentsCreateTime: formattedDate,
			        commentsUserId: this.addForm.commentsUserId,
			        commentsPostId: this.addForm.commentsPostId,
			        commentsUp: this.addForm.commentsUp,
			        commentsParentsId: this.btnId,
			        commentsInputShow: 0,
			      },
			      success: () => {
			        uni.showToast({
			          title: '回复成功',
			          icon: 'success'
			        });
			        this.replyComment = '';
			        this.btnId = '';
			        // 发送成功后刷新页面数据
			        this.getPost();
			      },
			      fail: () => {
			        uni.showToast({
			          title: '回复失败',
			          icon: 'error'
			        });
			      }
			    });
			  },
			onDivInput: function(event) {
				this.replyComment = event.target.value
			},
			getPost() {
				uni.request({
					url: this.$BASE_URL.baseUrl + '/community/post/' + this.postId,
					success: (res) => {
						this.postList = res.data.data;
						this.commentList = res.data.data.communityCommentsList
						console.log(this.commentList)
						const nestedComments = this.nestComments(this.commentList);
						this.commentList = nestedComments;
					}
				})
			},
			getBtnId(id) {
				this.btnId = id,
				console.log("this.btnId" + this.btnId)
			},
			padZero(num) {
				return num < 10 ? `0${num}` : num;
			},
			
		},
	}
</script>

<style lang="scss" scoped>
	.all {
		background-color: #f8f4e9;
		padding: 20rpx;
		font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
	}
	
	/* 非遗风格设计元素 */
	.divider {
		height: 2rpx;
		background: linear-gradient(to right, transparent, #d4a373, transparent);
		margin: 20rpx 0;
	}
	
	/* 帖子样式 */
	.post {
		background-color: #fff9f0;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		border: 1rpx solid #e9d8c5;
	}
	
	.post-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		border: 2rpx solid #d4a373;
	}
	
	.user-info {
		margin-left: 20rpx;
		display: flex;
		flex-direction: column;
	}
	
	.name {
		font-size: 32rpx;
		color: #5e3a1e;
		font-weight: bold;
	}
	
	.time {
		font-size: 24rpx;
		color: #a68a64;
		margin-top: 6rpx;
	}
	
	.post-content {
		padding: 10rpx 0;
	}
	
	.title {
		font-size: 36rpx;
		color: #3a2818;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.details {
		font-size: 30rpx;
		color: #5e4d3a;
		line-height: 1.6;
	}
	
	/* 评论区域 */
	.comment-section {
		margin-top: 40rpx;
	}
	
	.comment-item {
		background-color: #fff9f0;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 30rpx;
		border: 1rpx solid #e9d8c5;
	}
	
	.comment-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}
	
	.action-buttons {
		display: flex;
		margin-left: auto;
	}
	
	.action-btn {
		display: flex;
		align-items: center;
		margin-left: 30rpx;
		color: #d4a373;
	}
	
	.action-text {
		font-size: 26rpx;
		margin-left: 8rpx;
	}
	
	.comment-content {
		font-size: 28rpx;
		color: #5e4d3a;
		line-height: 1.5;
		padding-left: 100rpx;
	}
	
	/* 回复列表 */
	.reply-list {
		margin-top: 20rpx;
		padding-left: 80rpx;
	}
	
	.reply-item {
		background-color: #f8f4e9;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		border-left: 4rpx solid #d4a373;
	}
	
	.reply-header {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
	}
	
	.reply-content {
		font-size: 26rpx;
		color: #5e4d3a;
		line-height: 1.5;
		padding-left: 80rpx;
	}
	
	.reply-to {
		color: #d4a373;
		margin-right: 10rpx;
	}
	
	/* 输入框 */
	.reply-input-container {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		padding: 20rpx;
		background-color: #f8f4e9;
		border-radius: 12rpx;
	}
	
	.reply-input {
		flex: 1;
		height: 70rpx;
		padding: 0 20rpx;
		background-color: #fff;
		border-radius: 8rpx;
		border: 1rpx solid #d4a373;
		font-size: 28rpx;
		color: #5e4d3a;
	}
	
	.bottom-input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #fff9f0;
		border-top: 1rpx solid #e9d8c5;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.comment-input {
		flex: 1;
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #fff;
		border-radius: 8rpx;
		border: 1rpx solid #d4a373;
		font-size: 28rpx;
		color: #5e4d3a;
		margin-right: 20rpx;
	}
	
	.send-btn {
		background-color: #d4a373;
		color: #fff;
		border-radius: 8rpx;
		padding: 0 30rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border: none;
	}
	
	/* 加入按钮 */
	.join-btn {
		position: fixed;
		bottom: 160rpx;
		right: 40rpx;
		width: 120rpx;
		height: 120rpx;
		background-color: #d4a373;
		border-radius: 50%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		z-index: 100;
	}
	
	.join-btn text {
		font-size: 24rpx;
		margin-top: 8rpx;
	}
</style>
